import AppConfig from "../AppConfig";

const API_CODE = require("apiCode");
let apiRequest = require("apiRequest");

let _openId = null;
const OPEN_ID_KEY = 'OPEN_ID_KEY_FROM_SEVER';

function getOpenIdFromLocalData() {
  if(_openId)
    return _openId;
  let _openId = LocalData.getItem(OPEN_ID_KEY, null);
  return _openId;
}

function getOpenIdFromCode2Session(callback) {
  //如果已经取到openid, 就直接返回
  if (_openId) {
    callback(null, _openId);
    return;
  }
  _openId = LocalData.getItem(OPEN_ID_KEY, null);
  if (!_openId) {
    PlatformUtils.login(() => {
      if (!Global.LoginState.isLogin) {
        callback && callback("未登录");
        return;
      }
      let code = Global.LoginState.loginCode;
      let url = `${AppConfig.CODE_2_SESSION_URL}?appid=${AppConfig.APP_ID}&code=${code}`;
      wx.request({
        url,
        success(res) {
          console.log(res.data);
          res = res.data;
          if (res.code !== API_CODE.SUCCEED) {
            PlatformUtils.sendLogEvent('从服务器取OpenId失败', {err: JSON.stringify(res)});
            callback && callback('取OpenId失败');
            return;
          }
          _openId = res.openid;
          LocalData.setItem(OPEN_ID_KEY, _openId);
          callback && callback(null, _openId);
        },
        fail(res) {
          console.warn(res);
          PlatformUtils.sendLogEvent('从服务器取OpenId失败', {err: JSON.stringify(res)});
          callback && callback(res);
        }
      })
    });
  } else {
    //返回本地的openId
    callback(null, _openId);
  }
}


function isEmptyGameData(gameData) {
  if (!gameData) {
    return true;
  }
  return Object.keys(gameData).length === 0;
}

module.exports = {
  getOpenIdFromLocalData,
  getOpenIdFromCode2Session,
  getOpenIdFromSelfServer,
  replaceFullGameDataToSelfServer,
  loadGameDataFromSelfServer,
  saveGameDataToSelfServer,
};
